package com.lwf.smartseniorcare.service;

import com.lwf.smartseniorcare.dto.HealthRecordDTO;
import com.lwf.smartseniorcare.entity.Elderly;
import com.lwf.smartseniorcare.entity.HealthRecord;
import com.lwf.smartseniorcare.repository.ElderlyRepository;
import com.lwf.smartseniorcare.repository.HealthRecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class HealthRecordService {

    @Autowired
    HealthRecordRepository healthRecordRepository;

    @Autowired
    ElderlyRepository elderlyRepository;

    // Convert Entity to DTO
    private HealthRecordDTO convertToDTO(HealthRecord record) {
        HealthRecordDTO dto = new HealthRecordDTO();
        dto.setId(record.getId());
        dto.setElderlyId(record.getElderly().getId());
        dto.setRecordDate(record.getRecordDate());
        dto.setBloodPressureSystolic(record.getBloodPressureSystolic());
        dto.setBloodPressureDiastolic(record.getBloodPressureDiastolic());
        dto.setHeartRate(record.getHeartRate());
        dto.setBloodSugar(record.getBloodSugar());
        dto.setWeight(record.getWeight());
        dto.setSymptoms(record.getSymptoms());
        dto.setNotes(record.getNotes());
        return dto;
    }

    // Convert DTO to Entity
    private HealthRecord convertToEntity(HealthRecordDTO dto) {
        HealthRecord record = new HealthRecord();
        if (dto.getId() != null) {
            record.setId(dto.getId());
        }
        Elderly elderly = elderlyRepository.findById(dto.getElderlyId())
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + dto.getElderlyId()));
        record.setElderly(elderly);
        record.setRecordDate(dto.getRecordDate());
        record.setBloodPressureSystolic(dto.getBloodPressureSystolic());
        record.setBloodPressureDiastolic(dto.getBloodPressureDiastolic());
        record.setHeartRate(dto.getHeartRate());
        record.setBloodSugar(dto.getBloodSugar());
        record.setWeight(dto.getWeight());
        record.setSymptoms(dto.getSymptoms());
        record.setNotes(dto.getNotes());
        return record;
    }

    public List<HealthRecordDTO> getAllHealthRecords() {
        return healthRecordRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public HealthRecordDTO getHealthRecordById(Long id) {
        HealthRecord record = healthRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Health record not found with id: " + id));
        return convertToDTO(record);
    }

    public HealthRecordDTO createHealthRecord(HealthRecordDTO healthRecordDTO) {
        HealthRecord record = convertToEntity(healthRecordDTO);
        record = healthRecordRepository.save(record);
        return convertToDTO(record);
    }

    public HealthRecordDTO updateHealthRecord(Long id, HealthRecordDTO healthRecordDTO) {
        HealthRecord existingRecord = healthRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Health record not found with id: " + id));
        
        HealthRecord updatedRecord = convertToEntity(healthRecordDTO);
        updatedRecord.setId(id); // Ensure we don't create a new entity
        
        updatedRecord = healthRecordRepository.save(updatedRecord);
        return convertToDTO(updatedRecord);
    }

    public void deleteHealthRecord(Long id) {
        HealthRecord record = healthRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Health record not found with id: " + id));
        healthRecordRepository.delete(record);
    }

    public List<HealthRecordDTO> getHealthRecordsByElderly(Long elderlyId) {
        Elderly elderly = elderlyRepository.findById(elderlyId)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + elderlyId));
        return healthRecordRepository.findByElderlyOrderByRecordDateDesc(elderly).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public List<HealthRecordDTO> getHealthRecordsByElderlyAndDateRange(Long elderlyId, Date startDate, Date endDate) {
        Elderly elderly = elderlyRepository.findById(elderlyId)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + elderlyId));
        return healthRecordRepository.findByElderlyAndRecordDateBetween(elderly, startDate, endDate).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    public List<HealthRecordDTO> getRecentHealthRecordsByElderly(Long elderlyId) {
        Elderly elderly = elderlyRepository.findById(elderlyId)
                .orElseThrow(() -> new RuntimeException("Elderly not found with id: " + elderlyId));
        return healthRecordRepository.findTop10ByElderlyOrderByRecordDateDesc(elderly).stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
}
